<?php

namespace app\admin\controller\pt;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * 工作分配管理
 *
 * @icon fa fa-user-plus
 */
class JobOffer extends Backend
{
    /**
     * JobOffer模型对象
     * @var \app\admin\model\pt\JobOffer
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pt\JobOffer;
        $this->view->assign("jobOfferPositions", $this->model->getJobOfferPositionList());
        $this->view->assign("jobOfferStatus", $this->model->getJobOfferStatusList());
    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with("order")
            ->where($where)
            // ->where("user_id", $this->auth->id)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }



    public function confirm($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (!\in_array($params['offer_status'], [2, 3])) {
            $this->error('请选择确认状态');
        }
        if ($params['offer_status'] == 2) {
            if (empty($params['remark'])) {
                $params['remark'] = "同意";
            }

        }
        if ($params['offer_status'] == 3) {
            if (empty($params['remark'])) {
                $this->error('请在审核意见填写拒绝原因');
            }
        }

        //确认时间
        $params['confirm_time'] = date('Y-m-d H:i:s');
        //排除前台提交过来的字段
        $params = $this->preExcludeFields($params);
        Db::startTrans();
        try {
            //修改审核状态更新
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }


        $this->success();

    }
}